<?php
session_start();

// 如果已经登录，重定向到用户主页
if (isset($_SESSION['user_id'])) {
    header('Location: user_home.php');
    exit();
}

require 'database.php';

$error_message = '';
$blocked_message = '';

// 获取客户端IP地址
function getClientIP() {
    $ip_keys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
    foreach ($ip_keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
    }
    return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}

$client_ip = getClientIP();

// 检查IP是否被封锁
function isIPBlocked($conn, $ip) {
    $sql = "SELECT blocked_time, attempts_count FROM blocked_ips WHERE ip_address = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $ip);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $blocked_time = strtotime($row['blocked_time']);
        $current_time = time();

        // 检查是否超过1小时
        if (($current_time - $blocked_time) < 3600) {
            return true;
        } else {
            // 超过1小时，解除封锁
            $delete_sql = "DELETE FROM blocked_ips WHERE ip_address = ?";
            $delete_stmt = $conn->prepare($delete_sql);
            $delete_stmt->bind_param('s', $ip);
            $delete_stmt->execute();
            return false;
        }
    }
    return false;
}

// 记录登录尝试
function recordLoginAttempt($conn, $ip, $username, $success) {
    $sql = "INSERT INTO login_attempts (ip_address, username, success) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ssi', $ip, $username, $success);
    $stmt->execute();
}

// 检查失败次数并封锁IP
function checkAndBlockIP($conn, $ip) {
    // 检查最近1小时内的失败次数
    $sql = "SELECT COUNT(*) as failed_count FROM login_attempts
            WHERE ip_address = ? AND success = 0 AND attempt_time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $ip);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    if ($row['failed_count'] >= 3) {
        // 封锁IP
        $block_sql = "INSERT INTO blocked_ips (ip_address, attempts_count) VALUES (?, ?)
                      ON DUPLICATE KEY UPDATE attempts_count = ?, blocked_time = CURRENT_TIMESTAMP";
        $block_stmt = $conn->prepare($block_sql);
        $attempts = $row['failed_count'];
        $block_stmt->bind_param('sii', $ip, $attempts, $attempts);
        $block_stmt->execute();
        return true;
    }
    return false;
}

// 创建必要的数据表
try {
    // 创建登录尝试记录表
    $conn->query("
        CREATE TABLE IF NOT EXISTS login_attempts (
            id INT AUTO_INCREMENT PRIMARY KEY,
            ip_address VARCHAR(45) NOT NULL,
            username VARCHAR(50),
            attempt_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            success BOOLEAN DEFAULT FALSE,
            INDEX idx_ip_time (ip_address, attempt_time)
        )
    ");

    // 创建IP封锁表
    $conn->query("
        CREATE TABLE IF NOT EXISTS blocked_ips (
            id INT AUTO_INCREMENT PRIMARY KEY,
            ip_address VARCHAR(45) UNIQUE NOT NULL,
            blocked_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            attempts_count INT DEFAULT 0
        )
    ");
} catch (Exception $e) {
    error_log('Database table creation error: ' . $e->getMessage());
}

// 检查IP是否被封锁
if (isIPBlocked($conn, $client_ip)) {
    $blocked_message = '您的IP地址因多次登录失败已被暂时封锁，请1小时后重试或联系管理员';
}

// 处理登录请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$blocked_message) {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (empty($username) || empty($password)) {
        $error_message = '请输入OA登录账号和密码';
    } else {
        try {
            // 查询用户信息
            $sql = "SELECT user_id, name, password_hash, position FROM staff WHERE user_id = ? AND serving = TRUE";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('s', $username);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                $user = $result->fetch_assoc();

                // 验证密码
                $password_valid = false;
                if (password_get_info($user['password_hash'])['algo']) {
                    // 使用password_verify验证哈希密码
                    $password_valid = password_verify($password, $user['password_hash']);
                } else {
                    // 兼容旧的明文密码
                    $password_valid = ($password === $user['password_hash']);
                }

                if ($password_valid) {
                    // 登录成功
                    recordLoginAttempt($conn, $client_ip, $username, 1);

                    // 设置会话
                    $_SESSION['user_id'] = $user['user_id'];
                    $_SESSION['username'] = $user['name'];
                    $_SESSION['position'] = $user['position'];
                    $_SESSION['login_time'] = time();
                    $_SESSION['login_ip'] = $client_ip;

                    // 更新最后登录时间和在线状态
                    $update_sql = "UPDATE staff SET latest_login = CURRENT_TIMESTAMP, online_status = 'true' WHERE user_id = ?";
                    $update_stmt = $conn->prepare($update_sql);
                    $update_stmt->bind_param('s', $username);
                    $update_stmt->execute();

                    header('Location: user_home.php');
                    exit();
                } else {
                    // 密码错误
                    recordLoginAttempt($conn, $client_ip, $username, 0);
                    $error_message = 'OA登录账号或密码错误';

                    // 检查是否需要封锁IP
                    if (checkAndBlockIP($conn, $client_ip)) {
                        $blocked_message = '登录失败次数过多，您的IP地址已被暂时封锁1小时';
                    }
                }
            } else {
                // 用户不存在
                recordLoginAttempt($conn, $client_ip, $username, 0);
                $error_message = 'OA登录账号或密码错误';

                // 检查是否需要封锁IP
                if (checkAndBlockIP($conn, $client_ip)) {
                    $blocked_message = '登录失败次数过多，您的IP地址已被暂时封锁1小时';
                }
            }
        } catch (Exception $e) {
            $error_message = '登录时发生错误，请稍后重试';
            error_log('Login error: ' . $e->getMessage());
        }
    }
}

$page_title = '用户登录 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <h1 class="login-title">考务管理系统</h1>
                <p class="login-subtitle">请使用您的OA账号登录</p>
            </div>

            <?php if ($blocked_message): ?>
                <div class="alert alert-error">
                    <?php echo htmlspecialchars($blocked_message); ?>
                </div>
            <?php elseif ($error_message): ?>
                <div class="alert alert-error">
                    <?php echo htmlspecialchars($error_message); ?>
                </div>
            <?php endif; ?>

            <?php if (!$blocked_message): ?>
                <form method="POST" action="index.php" id="loginForm">
                    <div class="form-group">
                        <label for="username" class="form-label">OA登录账号</label>
                        <input
                            type="text"
                            id="username"
                            name="username"
                            class="form-control"
                            placeholder="请输入您的OA登录账号"
                            value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>"
                            required
                            autofocus
                        >
                    </div>

                    <div class="form-group">
                        <label for="password" class="form-label">登录密码</label>
                        <input
                            type="password"
                            id="password"
                            name="password"
                            class="form-control"
                            placeholder="请输入您的登录密码"
                            required
                        >
                    </div>

                    <div class="form-group">
                        <button type="submit" class="btn btn-primary w-100">登录系统</button>
                    </div>
                </form>

                <div class="form-group">
                    <a href="reset_password.php" class="btn w-100" style="text-align: center;">修改密码</a>
                </div>
            <?php else: ?>
                <div class="form-group">
                    <a href="admin_panel.php" class="btn btn-warning w-100" style="text-align: center;">联系管理员</a>
                </div>
            <?php endif; ?>

            <div class="text-center mt-3">
                <p style="color: var(--text-secondary); font-size: 12px;">
                    如果您忘记了密码，请使用身份证号重置密码<br>
                    登录失败3次将暂时封锁IP地址1小时
                </p>
            </div>
        </div>
    </div>

    <script>
        // 登录表单验证
        document.getElementById('loginForm')?.addEventListener('submit', function(e) {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();

            if (!username) {
                alert('请输入OA登录账号');
                document.getElementById('username').focus();
                e.preventDefault();
                return false;
            }

            if (!password) {
                alert('请输入登录密码');
                document.getElementById('password').focus();
                e.preventDefault();
                return false;
            }

            return true;
        });

        // 回车键快捷登录
        document.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && document.getElementById('loginForm')) {
                document.getElementById('loginForm').submit();
            }
        });
    </script>
</body>
</html>